package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.AccountFlow;
import com.zhentao.service.AccountFlowService;
import com.zhentao.util.ExcelExportUtil;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账户流水管理接口
 */
@RestController
@RequestMapping("/finance/accountFlow")
public class AccountFlowController {

    @Autowired
    private AccountFlowService accountFlowService;

    /**
     * 分页查询账户流水
     */
    @GetMapping("/list")
    public Result<Page<AccountFlow>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long accountId,
            @RequestParam(required = false) String billType,
            @RequestParam(required = false) String flowType) {
        
        try {
            Page<AccountFlow> page = new Page<>(current, size);
            QueryWrapper<AccountFlow> wrapper = new QueryWrapper<>();
            
            if (accountId != null) {
                wrapper.eq("account_id", accountId);
            }
            if (StringUtils.hasText(billType)) {
                wrapper.eq("bill_type", billType);
            }
            if (StringUtils.hasText(flowType)) {
                wrapper.eq("flow_type", flowType);
            }
            wrapper.orderByDesc("create_time");
            
            IPage<AccountFlow> result = accountFlowService.page(page, wrapper);
            return Result.success((Page<AccountFlow>) result);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询账户流水
     */
    @GetMapping("/{id}")
    public Result<AccountFlow> getById(@PathVariable Long id) {
        try {
            AccountFlow accountFlow = accountFlowService.getById(id);
            if (accountFlow != null) {
                return Result.success(accountFlow);
            } else {
                return Result.error("账户流水不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增账户流水
     */
    @PostMapping("/add")
    public Result<String> add(@RequestBody AccountFlow accountFlow) {
        try {
            if (accountFlow.getCreateTime() == null) {
                accountFlow.setCreateTime(new Date());
            }
            
            boolean success = accountFlowService.save(accountFlow);
            if (success) {
                return Result.success("新增成功");
            } else {
                return Result.error("新增失败");
            }
        } catch (Exception e) {
            return Result.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 修改账户流水
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody AccountFlow accountFlow) {
        try {
            boolean success = accountFlowService.updateById(accountFlow);
            if (success) {
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            return Result.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 删除账户流水
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        try {
            boolean success = accountFlowService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除账户流水
     */
    @PostMapping("/batchDelete")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        try {
            boolean success = accountFlowService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    public Result<Object> getStats() {
        try {
            QueryWrapper<AccountFlow> wrapper = new QueryWrapper<>();
            
            List<AccountFlow> accountFlows = accountFlowService.list(wrapper);
            
            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal monthlyAmount = BigDecimal.ZERO;
            int totalCount = accountFlows.size();
            
            // 计算总金额和本月金额
            for (AccountFlow flow : accountFlows) {
                if (flow.getAmount() != null) {
                    totalAmount = totalAmount.add(flow.getAmount());
                    
                    // 检查是否是本月的数据（简化处理）
                    if (flow.getCreateTime() != null) {
                        // 将java.util.Date转换为java.time.LocalDate
                        java.time.Instant instant = flow.getCreateTime().toInstant();
                        java.time.ZoneId zoneId = java.time.ZoneId.systemDefault();
                        java.time.LocalDate flowDate = instant.atZone(zoneId).toLocalDate();
                        
                        java.time.LocalDate now = java.time.LocalDate.now();
                        if (flowDate.getYear() == now.getYear() && flowDate.getMonth() == now.getMonth()) {
                            monthlyAmount = monthlyAmount.add(flow.getAmount());
                        }
                    }
                }
            }
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalAmount", totalAmount);
            stats.put("monthlyAmount", monthlyAmount);
            stats.put("totalCount", totalCount);
            
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 导出账户流水数据
     */
    @GetMapping("/export")
    public void export(AccountFlow query, HttpServletResponse response) throws IOException {
        try {
            QueryWrapper<AccountFlow> wrapper = new QueryWrapper<>();
            
            if (query != null) {
                if (query.getAccountId() != null) {
                    wrapper.eq("account_id", query.getAccountId());
                }
                if (query.getBillType() != null) {
                    wrapper.eq("bill_type", query.getBillType());
                }
                if (query.getFlowType() != null) {
                    wrapper.eq("flow_type", query.getFlowType());
                }
            }
            wrapper.orderByDesc("create_time");
            
            // 查询所有数据
            List<AccountFlow> accountFlows = accountFlowService.list(wrapper);
            
            // 准备Excel数据
            List<String> headers = new ArrayList<>();
            headers.add("流水编号");
            headers.add("账户ID");
            headers.add("金额");
            headers.add("流水类型");
            headers.add("单据类型");
            headers.add("单据编号");
            headers.add("创建时间");
            
            List<List<Object>> dataList = new ArrayList<>();
            for (AccountFlow flow : accountFlows) {
                List<Object> row = new ArrayList<>();
                row.add(flow.getId() != null ? flow.getId().toString() : "");
                row.add(flow.getAccountId() != null ? flow.getAccountId().toString() : "");
                row.add(flow.getAmount() != null ? flow.getAmount().toString() : "0.00");
                row.add(flow.getFlowType() != null ? flow.getFlowType() : "");
                row.add(flow.getBillType() != null ? flow.getBillType() : "");
                row.add(flow.getBillNo() != null ? flow.getBillNo() : "");
                row.add(flow.getCreateTime() != null ? flow.getCreateTime().toString() : "");
                dataList.add(row);
            }
            
            // 导出Excel
            String fileName = "账户流水数据_" + java.time.LocalDate.now();
            ExcelExportUtil.exportToResponse(response, fileName, headers, dataList);
            
        } catch (Exception e) {
            // 如果导出失败，返回错误信息
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("导出失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
